package com.ftd.messagelistener.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import com.ftd.messagelistener.activity.AlarmActivity;
import com.ftd.messagelistener.activity.MainActivity;
import com.ftd.messagelistener.base.Constants;
import com.ftd.messagelistener.service.SMSService;

import static android.content.Intent.ACTION_SCREEN_ON;

/**
 * tangxianfeng
 * 2021.11.28
 */
public class SMSReceiver extends BroadcastReceiver {

    private static final String TAG="SMSReceiver";

    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    public static final String SMS_DELIVER = "android.provider.Telephony.SMS_DELIVER";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "收到广播"+intent.getAction());
        switch (intent.getAction()) {
            case SMS_RECEIVED:
            case SMS_DELIVER:
                Log.e(TAG, "收到短信");
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Object[] pdus = (Object[]) bundle.get("pdus");              //这个.get("pdus")中的pdus字符是固定的SMS pdus数组
                    SmsMessage[] messages = new SmsMessage[pdus.length];
                    for (int i = 0; i < pdus.length; i++)
                        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    for (SmsMessage message : messages) {
                        String msg = message.getMessageBody();
                        String phone = message.getOriginatingAddress();
                        Intent ser=new Intent(context,SMSService.class);
                        ser.setPackage("com.ftd.messagelistener.service");
                        ser.setAction(Constants.SMSAction);
                        ser.putExtra("msg",msg);
                        ser.putExtra("phone",phone);
                        context.startService(ser);
                    }
                }
                break;
        }
    }
}
